package com.atguigu.gmall.payment.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.entity.PaymentInfoEntity;
import com.atguigu.gmall.payment.feign.GmallOmsClient;
import com.atguigu.gmall.payment.mapper.PaymentMapper;
import com.atguigu.gmall.payment.vo.PayAsyncVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PaymentService {
    @Autowired
    GmallOmsClient omsClient;
    @Autowired
    PaymentMapper paymentMapper;
    public OrderEntity getOrderInfo(String orderToken) {
        ResponseVo<OrderEntity> orderByToken = omsClient.getOrderByToken(orderToken);
       return orderByToken.getData();
    }

    public void paySuccess(PayAsyncVo vo) {
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setId(Long.valueOf(vo.getPassback_params()));
        paymentInfoEntity.setCallbackContent(JSON.toJSONString(vo));
        paymentInfoEntity.setCallbackTime(new Date());
        paymentInfoEntity.setPaymentStatus(1);
        this.paymentMapper.update(paymentInfoEntity,new UpdateWrapper<PaymentInfoEntity>().
                eq("out_trade_no",vo.getOut_trade_no()));
    }

    public int initOrderState(String orderToken, OrderEntity orderEntity, PaymentInfoEntity paymentInfoEntity) {
        paymentInfoEntity.setOutTradeNo(orderToken);
        paymentInfoEntity.setPaymentType(1);
        paymentInfoEntity.setPaymentStatus(0);
        paymentInfoEntity.setTotalAmount(orderEntity.getTotalAmount());
        paymentInfoEntity.setSubject("谷粒商城商品");
        paymentInfoEntity.setCreateTime(new Date());
     return  this.paymentMapper.insert(paymentInfoEntity);
    }
}
